package com.droid.lib.controls.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import com.droid.lib.controls.R;

/**
 * Created by 仪表盘多半圆 on 2018/08/23
 */

public class InstruClock extends View {

    private static final int DEFAULT_OUT_RADIUS = 100;
    private static final int DEFAULT_INNER_RADIUS = 60;
    private static final int DEFAULT_DEVIDER_LINE = 10;

    private int mOutRadius;
    private Paint mRingPaint;
    private Paint mTitlePaint;
    private RectF mRect;
    private Paint mLinePaint;
    private Paint mTextPaint;
    private Paint.FontMetrics fontMetrics;
    private Paint.FontMetrics titleMetrics;
    private Paint mDownTextPaint;
    private int currentValue;
    /**
     * 边圈的颜色1
     */
    private int colorOne = Color.parseColor("#94c9b2");
    /**
     * 边圈的颜色2
     */
    private int colorTwo = Color.parseColor("#5e859b");
    /**
     * 边圈的颜色3
     */
    private int colorThree = Color.parseColor("#bf352e");
    /**
     * 圆形中心颜色
     */
    private int colorCenter = getDrawingCacheBackgroundColor();
    /**
     * 边圈线的颜色
     */
    private int lineColor=Color.WHITE;
    private int textColor=Color.WHITE;
    /**
     * 设置图表颜色
     * @param colors 0，1,2设置仪表盘边圈的三个颜色，3中间圆型的颜色，4边圈刻度线的颜色，5百分比文字的颜色,6标题颜色
     */
    public void setBarColor(int[] colors) {
        colorOne = colors[0];
        colorTwo = colors[1];
        colorThree = colors[2];
        colorCenter = colors[3];
        mLinePaint.setColor(colors[4]);
        mTextPaint.setColor(colors[5]);
        mDownTextPaint.setColor(colors[6]);
    }
    public InstruClock(Context context) {
        this(context, null);
    }

    public InstruClock(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public InstruClock(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initAttrs(context, attrs);
        initPaint();
    }

    private void initAttrs(Context context, AttributeSet attrs) {
        final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.InstruClock);
        mOutRadius = (int) attributes.getDimension(R.styleable.InstruClock_outRadius, DEFAULT_OUT_RADIUS);
        colorOne=attributes.getColor(R.styleable.InstruClock_barColorOne,Color.parseColor("#94c9b2"));
        colorTwo=attributes.getColor(R.styleable.InstruClock_barColorTwo,Color.parseColor("#5e859b"));
        colorThree=attributes.getColor(R.styleable.InstruClock_barColorThree,Color.parseColor("#bf352e"));
        lineColor=attributes.getColor(R.styleable.InstruClock_barLineColor,Color.WHITE);
        textColor=attributes.getColor(R.styleable.InstruClock_barTextColor,Color.WHITE);
        colorCenter = attributes.getColor(R.styleable.InstruClock_barCenter,ContextCompat.getColor(getContext(), R.color.color_menu_bg));
        attributes.recycle();
    }

    private void initPaint() {
        mRingPaint = new Paint();
        mRingPaint.setStyle(Paint.Style.FILL);
        mRingPaint.setAntiAlias(true);

        mLinePaint = new Paint();
        mLinePaint.setStyle(Paint.Style.STROKE);
        mLinePaint.setAntiAlias(true);
        mLinePaint.setColor(lineColor);
        mLinePaint.setStrokeWidth(4);

        mTitlePaint = new Paint();
        mTitlePaint.setTextSize(25);
        mTitlePaint.setColor(textColor);
        mTitlePaint.setAntiAlias(true);
        mTitlePaint.setTextAlign(Paint.Align.CENTER);
        titleMetrics = mTitlePaint.getFontMetrics();

        mTextPaint = new Paint();
        mTextPaint.setTextSize(40);
        mTextPaint.setColor(textColor);
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
        fontMetrics = mTextPaint.getFontMetrics();

        mDownTextPaint = new Paint();
        mDownTextPaint.setTextSize(40);
        mDownTextPaint.setColor(textColor);
        mDownTextPaint.setAntiAlias(true);
        mDownTextPaint.setTextAlign(Paint.Align.CENTER);
        mDownTextPaint.setStrokeWidth(10);
        mDownTextPaint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int mWidth, mHeight;
        if (widthMode == MeasureSpec.EXACTLY) {
            mWidth = widthSize;
        } else {
            mWidth = getPaddingLeft() + mOutRadius * 3 + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                mWidth = Math.min(mWidth, widthSize);
            }
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            mHeight = heightSize;
        } else {
            mHeight = getPaddingTop() + mOutRadius * 2 + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                mHeight = Math.max(mHeight, heightSize);
            }
        }
        setMeasuredDimension(mWidth, mHeight);
        mOutRadius = Math.min((getMeasuredWidth() - getPaddingLeft() - getPaddingRight()), getMeasuredHeight() - getPaddingTop() - getPaddingBottom()) / 2;
        mRect = new RectF(-mOutRadius, -mOutRadius, mOutRadius, mOutRadius);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(getMeasuredWidth() / 2, getMeasuredHeight() / 2);
        mRingPaint.setColor(colorOne);
        canvas.drawArc(mRect, 120, 60, true, mRingPaint);
        mRingPaint.setColor(colorTwo);
        canvas.drawArc(mRect, 180, 240, true, mRingPaint);
        mRingPaint.setColor(colorThree);
        canvas.drawArc(mRect, 0, 60, true, mRingPaint);
        mRingPaint.setColor(colorCenter);
        canvas.drawCircle(0, 0, mOutRadius * 7 / 8, mRingPaint);
        canvas.rotate(120);
        for (int i = 0; i < 51; i++) {
            if (i % 5 == 0) {

                canvas.drawLine(mOutRadius, 0, mOutRadius * 7 / 8, 0, mLinePaint);//长线
                canvas.save();
                if (i < 6) {
                    mTextPaint.setColor(colorOne);
                } else if (i < 41) {
                    mTextPaint.setColor(colorTwo);
                } else {
                    mTextPaint.setColor(colorThree);
                }
                canvas.translate(mOutRadius * 7 / 8 - mTextPaint.measureText(String.valueOf(i / 5)), 0);
                canvas.rotate(240 - i * 6);
                canvas.drawText(String.valueOf(i / 5), 0, String.valueOf(i / 5).length(), 0, (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom, mTextPaint);
                canvas.restore();
            } else {
                canvas.drawLine(mOutRadius, 0, mOutRadius - 10, 0, mLinePaint);//短线
            }
            canvas.rotate(6);
        }

        if (currentValue <= 20) {
            mDownTextPaint.setColor(colorOne);
        } else if (currentValue <= 80) {
            mDownTextPaint.setColor(colorTwo);
        } else {
            mDownTextPaint.setColor(colorThree);
        }
        canvas.rotate(-66);
        canvas.drawText("完成率",0,-140,mTitlePaint);
        canvas.rotate(66);
        canvas.rotate(-66);
        canvas.drawText((float)currentValue / (float)10 + "%", 0, mOutRadius * 2 / 3, mDownTextPaint);

        canvas.rotate(120 + currentValue * 3);
        int d = dp2px(5); // 指针由两个等腰三角形构成，d为共底边长的一半
        Path path = new Path();
        float[] p1 = getCoordinatePoint(d, 0 - 90);
        path.moveTo(p1[0], p1[1]);
        float[] p2 = getCoordinatePoint(mOutRadius/3*2, 0);
        path.lineTo(p2[0], p2[1]);
        float[] p3 = getCoordinatePoint(d, 0 + 90);
        path.lineTo(p3[0], p3[1]);
        float[] p4 = getCoordinatePoint(20, 0 - 180);
        path.lineTo(p4[0], p4[1]);
        path.close();
        canvas.drawPath(path,mDownTextPaint);

    }
//    @Override
//    protected void onDraw(Canvas canvas) {
//        super.onDraw(canvas);
//        canvas.translate(getMeasuredWidth() / 2, getMeasuredHeight() / 2);
//        mRingPaint.setColor(Color.parseColor("#94c9b2"));
//        canvas.drawArc(mRect, 180, 156, true, mRingPaint);
//        mRingPaint.setColor(Color.parseColor("#5e859b"));
//        canvas.drawArc(mRect, 216, 120, true, mRingPaint);
//        mRingPaint.setColor(Color.parseColor("#bf352e"));
//        canvas.drawArc(mRect, 0, -36, true, mRingPaint);
//        mRingPaint.setColor(Color.parseColor("#45445c"));
//        canvas.drawCircle(0, 0, mOutRadius * 7 / 8, mRingPaint);
//        canvas.rotate(180);
//        for (int i = 0; i < 51; i++) {
//            if (i % 5 == 0) {
//
//                canvas.drawLine(mOutRadius, 0, mOutRadius * 7 / 8, 0, mLinePaint);//长线
//                canvas.save();
//                if (i < 6) {
//                    mTextPaint.setColor(Color.parseColor("#94c9b2"));
//                } else if (i < 41) {
//                    mTextPaint.setColor(Color.parseColor("#5e859b"));
//                } else {
//                    mTextPaint.setColor(Color.parseColor("#bf352e"));
//                }
//                canvas.translate(mOutRadius * 7 / 8 - mTextPaint.measureText(String.valueOf(i/5))-10, 0);
//                canvas.rotate((float)180 - (float)i*(float)3.6);
//                canvas.drawText(String.valueOf(i/5), 0, String.valueOf(i/5).length(), 0, (fontMetrics.bottom - fontMetrics.top) / 5 - fontMetrics.bottom, mTextPaint);
//                canvas.restore();
//            } else {
//                canvas.drawLine(mOutRadius, 0, mOutRadius - 10, 0, mLinePaint);//短线
//            }
//            canvas.rotate((float) 3.6);
//        }
//
//        if (currentValue <= 20) {
//            mDownTextPaint.setColor(Color.parseColor("#94c9b2"));
//        } else if (currentValue <= 80) {
//            mDownTextPaint.setColor(Color.parseColor("#5e859b"));
//        } else {
//            mDownTextPaint.setColor(Color.parseColor("#bf352e"));
//        }
//
//        canvas.rotate(-5);
//        canvas.drawText((float)currentValue / (float)10 + "%", 0, mOutRadius * 1 / 4, mDownTextPaint);
//        canvas.rotate(180+ (float)currentValue*(float)1.8);
//        int d = dp2px(5); // 指针由两个等腰三角形构成，d为共底边长的一半
//        Path path = new Path();
//        float[] p1 = getCoordinatePoint(d, 0 - 90);
//        path.moveTo(p1[0], p1[1]);
//        float[] p2 = getCoordinatePoint(160, 0);
//        path.lineTo(p2[0], p2[1]);
//        float[] p3 = getCoordinatePoint(d, 0 + 90);
//        path.lineTo(p3[0], p3[1]);
//        float[] p4 = getCoordinatePoint(20, 0 - 180);
//        path.lineTo(p4[0], p4[1]);
//        path.close();
//        canvas.drawPath(path,mDownTextPaint);
//
//    }
    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                Resources.getSystem().getDisplayMetrics());
    }

    private int sp2px(int sp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
                Resources.getSystem().getDisplayMetrics());
    }

    /**
     * 配置数据参数
     * @param data 该数据0-100之间
     */
    public void setCurrentData(int data) {

        ValueAnimator animator = ValueAnimator.ofInt(0, data);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                currentValue = (int) animation.getAnimatedValue();
                invalidate();
            }
        });
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.setDuration(2500);
        animator.start();
    }
    public float[] getCoordinatePoint(int radius, float angle) {
        float[] point = new float[2];
        float mCenterX=0;
        float mCenterY=0;
        double arcAngle = Math.toRadians(angle); //将角度转换为弧度
        if (angle < 90) {
            point[0] = (float) (mCenterX + Math.cos(arcAngle) * radius);
            point[1] = (float) (mCenterY + Math.sin(arcAngle) * radius);
        } else if (angle == 90) {
            point[0] = mCenterX;
            point[1] = mCenterY + radius;
        } else if (angle > 90 && angle < 180) {
            arcAngle = Math.PI * (180 - angle) / 180.0;
            point[0] = (float) (mCenterX - Math.cos(arcAngle) * radius);
            point[1] = (float) (mCenterY + Math.sin(arcAngle) * radius);
        } else if (angle == 180) {
            point[0] = mCenterX - radius;
            point[1] = mCenterY;
        } else if (angle > 180 && angle < 270) {
            arcAngle = Math.PI * (angle - 180) / 180.0;
            point[0] = (float) (mCenterX - Math.cos(arcAngle) * radius);
            point[1] = (float) (mCenterY - Math.sin(arcAngle) * radius);
        } else if (angle == 270) {
            point[0] = mCenterX;
            point[1] = mCenterY - radius;
        } else {
            arcAngle = Math.PI * (360 - angle) / 180.0;
            point[0] = (float) (mCenterX + Math.cos(arcAngle) * radius);
            point[1] = (float) (mCenterY - Math.sin(arcAngle) * radius);
        }

        return point;
    }
}
